package com.itheima.security.distributed.gateway.filter;

import com.itheima.security.distributed.gateway.common.JwtUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Objects;

/**
 * @author Administrator
 * @version 1.0
 **/
public class AuthFilter extends ZuulFilter {

    private static final String OAUTH_URL ="/uaa/oauth/token";

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();

        // 放行登录资源
        String requestURI = ctx.getRequest().getRequestURI();
        if (OAUTH_URL.equals(requestURI)) {
            return null;
        }

        String authorization = ctx.getRequest().getHeader("Authorization");
        if (StringUtils.isBlank(authorization)) {
            throw new RuntimeException("令牌不存在");
        }

        // 解析token
        String token = JwtUtil.getToken(authorization);
        Claims claims = JwtUtil.parseJWT(token);
        if (token == null || claims == null) {
            throw new RuntimeException("请求未经授权");
        }

        String userId = String.valueOf(claims.get("userId"));
        String mark = claims.get("mark", String.class);
        System.err.println("userId -> " + userId + " mark -> " + mark);

        // 判断token是否过期
        Object oAuth2AccessTokenValue = redisTemplate.opsForValue().get(token);
        if (Objects.isNull(oAuth2AccessTokenValue)) {
            throw new RuntimeException("令牌已过期");
        }
        return null;
    }

}
